﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class ItemOnDrag : MonoBehaviour,
    IBeginDragHandler, IDragHandler, IEndDragHandler,
    IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler
{
    private Transform originalParent;
    private Slot currentSlot;
    private BackpackData sourceBackpack;
    private int currentSlotID;

    public Text itemInfor;
    private static bool isOnDrag;
    GameObject bag;

    private void Awake()
    {
        bag = transform.parent.parent.parent.gameObject;
    }
    public void OnDisable()
    {
        if (isOnDrag || transform.parent == transform.root)
        {
            transform.SetParent(originalParent);
            transform.localPosition = Vector3.zero;
            isOnDrag = false;
        }

        // 确保显示状态重置
        if (transform.childCount > 2)
        {
            transform.GetChild(2).gameObject.SetActive(false);
        }

        // 恢复射线检测
        var cg = GetComponent<CanvasGroup>();
        if (cg != null)
            cg.blocksRaycasts = true;
    }
    // 拖拽开始
    public void OnBeginDrag(PointerEventData eventData)
    {
        // 缓存原父物体
        originalParent = transform.parent;

        // 找到 Slot
        currentSlot = GetComponentInParent<Slot>();
        if (currentSlot == null) return;

        // 找到背包数据，判断能否拖拽
        sourceBackpack = InventoryManager.instance.GetBackpackBySlot(currentSlot);
        if (sourceBackpack == null || !sourceBackpack.canDrag) return;

        // 缓存槽位 ID
        currentSlotID = currentSlot.slotID;

        // 移到顶层 Canvas (transform.root)
        transform.SetParent(transform.root);
        transform.position = eventData.position;

        // 禁用射线阻挡
        GetComponent<CanvasGroup>().blocksRaycasts = false;
        isOnDrag = true;
    }

    // 拖拽中
    public void OnDrag(PointerEventData eventData)
    {
        if (!isOnDrag) return;
        transform.position = eventData.position;
    }

    // 拖拽结束：鼠标松开时立即执行
    public void OnEndDrag(PointerEventData eventData)
    {
        if (!isOnDrag) return;
        isOnDrag = false;
        GetComponent<CanvasGroup>().blocksRaycasts = true;

        var hitGO = eventData.pointerCurrentRaycast.gameObject;
        if (hitGO != null)
        {
            // 1. 检查是否拖到SellBtn上
            if (hitGO.name == "SellBtn")
            {
                if (currentSlot != null)
                {
                    Item item = sourceBackpack.inventory.itemList[currentSlot.slotID];
                    if (item != null )
                    {
                        int totalValue = item.itemHeld * item.itemPrice;

                        // 2. 增加金币
                        var coinTextGO = GameObject.Find("CoinText");
                        if (coinTextGO != null)
                        {
                            var text = coinTextGO.GetComponent<Text>();
                            if (text != null && int.TryParse(text.text, out int curCoin))
                            {
                                text.text = (curCoin + totalValue).ToString();
                            }
                        }

                        // 3. 设置 itemHeld 为 0（也可替换为 sourceBackpack.inventory.itemList[currentSlot.slotID] = null;）
                        item.itemHeld = 0;

                        // 4. 刷新背包
                        InventoryManager.instance.RefreshAllBackpacks();

                        // 5. 删除拖拽物体
                        Destroy(gameObject);
                        return;
                    }
                }
            }

            // 6. 检查是否拖到其他合法槽
            Slot targetSlot = hitGO.GetComponentInParent<Slot>();
            if (targetSlot != null)
            {
                BackpackData targetBackpack = InventoryManager.instance.GetBackpackBySlot(targetSlot);
                if (targetBackpack != null && targetBackpack.canDrag)
                {
                    int targetID = targetSlot.slotID;
                    var srcList = sourceBackpack.inventory.itemList;
                    var tgtList = targetBackpack.inventory.itemList;

                    // 交换数据
                    Item temp = srcList[currentSlotID];
                    srcList[currentSlotID] = tgtList[targetID];
                    tgtList[targetID] = temp;

                    InventoryManager.instance.RefreshAllBackpacks();

                    // 挂回目标槽
                    transform.SetParent(targetSlot.transform);
                    transform.localPosition = Vector3.zero;
                    return;
                }
            }
        }

        // 其它情况归位
        transform.SetParent(originalParent);
        transform.localPosition = Vector3.zero;
    }



    // 光标进入显示信息
    public void OnPointerEnter(PointerEventData eventData)
    {

        // 先尝试取 info
        var slot = GetComponentInParent<Slot>();
        if (slot != null && itemInfor != null)
            itemInfor.text = slot.slotInfo;

        Debug.Log(slot.slotInfo);
        originalParent = transform.parent;
        if (!isOnDrag)
        {
            transform.SetParent(transform.root);
            if (transform.childCount > 2)
                transform.GetChild(2).gameObject.SetActive(true);
        }
    }

    // 光标离开隐藏信息
    public void OnPointerExit(PointerEventData eventData)
    {
        if (!isOnDrag)
        {
            transform.SetParent(originalParent);
            if (transform.childCount > 2)
                transform.GetChild(2).gameObject.SetActive(false);
        }
    }

    // 鼠标按下隐藏信息
    public void OnPointerDown(PointerEventData eventData)
    {
        if (transform.childCount > 2)
            transform.GetChild(2).gameObject.SetActive(false);
        transform.SetParent(originalParent);
    }
}
